import piniaPlugin from 'pinia-plugin-persistedstate'
import {ref,computed} from 'vue'
import {defineStore} from 'pinia'
import { useLoginStore } from './useLoginStore'
import { addCartAPI,getCartListAPI,delCartAPI} from '@/api/cart'
export const useCartStore = defineStore('cat',()=>{
    const list = ref([])

    const token = computed(()=>useLoginStore().userInfo.token)
    //获取最新购物车列表
    const updateCartList = async ()=>{
        const res = await getCartListAPI(token)
        list.value = res.data.result
    }

    //添加商品到购物车
    const addGoods = async (goods:object)=>{
        //用户已经登录
        if(token.value){
            await addCartAPI(goods)
            updateCartList()
        }else{
            const item = list.value.find((item)=>item.skuId === goods.skuId)
            if (item) {
                item.count += goods.count
            }else{
                list.value.push(goods)
            }
        }
    }
    //删除商品
    const delGoods = async (skuId:number)=>{
        if(token){
           await delCartAPI([skuId])
           updateCartList()
        }else{
            const index = list.value.findIndex((itme)=>{ itme.skuId === skuId})
            list.value.splice(index,1)
        }
    }
    //购物车内 商品总价格
    const getPrice = computed(()=>{
        let sum = 0;
        for(let i=0;i<list.value.length;i++){
            sum += list.value[i].count * list.value[i].price
        }
        return sum;
    })
    //购物车内 商品总数量
    const getGoodsCount = computed(()=>{
        let sum = 0;
        for(let i=0;i<list.value.length;i++){
            sum += list.value[i].count 
        }
        return sum;
    })
    //获取购物车列表
    const getCartList = async ()=>{
        const res = await getCartListAPI(token)
        return res.data.result
    }
    //单选
    const singleCheck = (skuId,selected)=>{
        const item = list.value.find((item)=>item.skuId === skuId)
        item.selected = selected
    }
    //全选
    const allCheck = (selected)=>{
        list.value.forEach(element => { element.selected = selected });
    }
    //清空本地购物车
    const clearCart = ()=>{
        list.value = []
    }
    return {
        list,
        addGoods,
        delGoods,
        getPrice,
        getGoodsCount,
        getCartList,
        singleCheck,
        allCheck,
        clearCart,
        updateCartList
    }
},{
    //持久化 
    persist:{
        paths:['list']
    }
})